package com.example.mywork;

import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MyAsyncTask extends AsyncTask<String,Integer,String> {

    @Override
    protected void onPreExecute() {

        MyAsyncTaskActivity.progressBar.setVisibility(View.VISIBLE);
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        String httpUrl = "https://www.baidu.com";
        String resultData = "";
        URL url = null;
        int step = 1;

        try {
          url = new URL(httpUrl);

            while (step <= 100) {
                publishProgress(step++);//step的值传递给onProgressUpdate(Integer... values)中的values参数
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.d("TAG","URL对象创建失败！");
        }

        if (url != null )
        {
            try {
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                //服务器返回数据字符流，网页文档编码一般为UTF-8
                InputStreamReader in = new InputStreamReader(urlConnection.getInputStream(),Charset.defaultCharset());
                //为输出创建BufferedRead
                BufferedReader bufferedReader = new BufferedReader(in);
                String inputLine = null;
                while ((inputLine = bufferedReader.readLine())!=null)
                {
                    resultData += inputLine+"\n";
                }
                in.close();
                urlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultData;
    }

    @Override
    protected void onPostExecute(String resultData) {
        if (resultData!=null)
        {
            MyAsyncTaskActivity.textView.setText(resultData);
        }else {
            MyAsyncTaskActivity.textView.setText("Sorry,the content is null");
        }
        MyAsyncTaskActivity.progressBar.setVisibility(View.GONE);   //移除ProgressBar
        MyAsyncTaskActivity.button.setText("DownLoad is done."); //异步任务返回的数据更新UI
        super.onPostExecute(resultData);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        MyAsyncTaskActivity.progressBar.setProgress(values[0]); //更新ProgressBar
        super.onProgressUpdate(values);
        MyAsyncTaskActivity.button.setText("后台正在下载...");

    }
}
